import React, { useState, useEffect } from 'react';
import {
  Card,
  Descriptions,
  Button,
  Space,
  message,
  Spin,
  Alert,
  Table,
  Tag,
  Avatar
} from 'antd';
import {
  ArrowLeftOutlined,
  EditOutlined,
  UserOutlined,
  MailOutlined,
  PhoneOutlined,
  HomeOutlined,
  BookOutlined
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import moment from 'moment';

const StudentDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { isAdmin } = useAuth();
  const [student, setStudent] = useState(null);
  const [bookings, setBookings] = useState([]);
  const [loading, setLoading] = useState(true);
  const [bookingsLoading, setBookingsLoading] = useState(false);

  useEffect(() => {
    loadStudentDetail();
    loadStudentBookings();
  }, [id]);

  const loadStudentDetail = async () => {
    try {
      setLoading(true);
      const data = await apiService.getStudentById(id);
      setStudent(data);
    } catch (error) {
      message.error('加载学生详情失败');
      console.error('加载学生详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadStudentBookings = async () => {
    try {
      setBookingsLoading(true);
      const data = await apiService.getBookingsByStudent(id);
      setBookings(data);
    } catch (error) {
      console.error('加载学生预订失败:', error);
    } finally {
      setBookingsLoading(false);
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'PENDING':
        return 'orange';
      case 'CONFIRMED':
        return 'green';
      case 'CANCELLED':
        return 'red';
      default:
        return 'default';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'PENDING':
        return '待确认';
      case 'CONFIRMED':
        return '已确认';
      case 'CANCELLED':
        return '已取消';
      default:
        return status;
    }
  };

  const getGenderText = (gender) => {
    return gender === 'MALE' ? '男' : '女';
  };

  const bookingColumns = [
    {
      title: '课程名称',
      dataIndex: ['course', 'name'],
      key: 'courseName',
      render: (text, record) => (
        <Button
          type="link"
          onClick={() => record && record.course && navigate(`/courses/${record.course.id}`)}
        >
          {text}
        </Button>
      )
    },
    {
      title: '课程代码',
      dataIndex: ['course', 'code'],
      key: 'courseCode'
    },
    {
      title: '教师',
      dataIndex: ['course', 'teacher', 'name'],
      key: 'teacherName'
    },
    {
      title: '学分',
      dataIndex: ['course', 'credit'],
      key: 'credit'
    },
    {
      title: '预订时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => moment(text).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="link"
          onClick={() => record && record.course && navigate(`/courses/${record.course.id}`)}
        >
          查看课程
        </Button>
      )
    }
  ];

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!student) {
    return (
      <Alert
        message="学生不存在"
        description="您访问的学生不存在或已被删除"
        type="error"
        showIcon
      />
    );
  }

  // 统计数据
  const confirmedBookings = bookings.filter(b => b.status === 'CONFIRMED').length;
  const pendingBookings = bookings.filter(b => b.status === 'PENDING').length;
  const cancelledBookings = bookings.filter(b => b.status === 'CANCELLED').length;
  const totalCredits = bookings
    .filter(b => b.status === 'CONFIRMED')
    .reduce((sum, b) => sum + (b.course?.credit || 0), 0);

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/students')}
        >
          返回学生列表
        </Button>
      </div>

      <Card
        title={
          <Space>
            <Avatar size={40} icon={<UserOutlined />} />
            {student.name}
            <Tag color={student.gender === 'MALE' ? 'blue' : 'pink'}>
              {getGenderText(student.gender)}
            </Tag>
          </Space>
        }
        extra={
          isAdmin() && (
            <Button
              icon={<EditOutlined />}
              onClick={() => navigate(`/students/${id}/edit`)}
            >
              编辑学生
            </Button>
          )
        }
      >
        <Descriptions bordered column={2}>
          <Descriptions.Item label="学号" span={1}>
            {student.studentId}
          </Descriptions.Item>
          <Descriptions.Item label="姓名" span={1}>
            <Space>
              <UserOutlined />
              {student.name}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="性别" span={1}>
            <Tag color={student.gender === 'MALE' ? 'blue' : 'pink'}>
              {getGenderText(student.gender)}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="邮箱" span={1}>
            <Space>
              <MailOutlined />
              {student.email}
            </Space>
          </Descriptions.Item>
          {student.phone && (
            <Descriptions.Item label="电话" span={1}>
              <Space>
                <PhoneOutlined />
                {student.phone}
              </Space>
            </Descriptions.Item>
          )}
          <Descriptions.Item label="专业" span={1}>
            {student.major}
          </Descriptions.Item>
          <Descriptions.Item label="班级" span={1}>
            {student.className}
          </Descriptions.Item>
          <Descriptions.Item label="入学年份" span={1}>
            {student.enrollmentYear}
          </Descriptions.Item>
          {student.birthDate && (
            <Descriptions.Item label="出生日期" span={1}>
              {moment(student.birthDate).format('YYYY-MM-DD')}
            </Descriptions.Item>
          )}
          <Descriptions.Item label="注册时间" span={1}>
            {moment(student.createdAt).format('YYYY-MM-DD HH:mm')}
          </Descriptions.Item>
          {student.address && (
            <Descriptions.Item label="地址" span={2}>
              <Space>
                <HomeOutlined />
                {student.address}
              </Space>
            </Descriptions.Item>
          )}
        </Descriptions>
      </Card>

      {/* 统计信息 */}
      <Card
        title="学习统计"
        style={{ marginTop: 16 }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-around', textAlign: 'center' }}>
          <div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
              {bookings.length}
            </div>
            <div>总预订数</div>
          </div>
          <div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
              {confirmedBookings}
            </div>
            <div>已确认课程</div>
          </div>
          <div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#faad14' }}>
              {pendingBookings}
            </div>
            <div>待确认课程</div>
          </div>
          <div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#f5222d' }}>
              {cancelledBookings}
            </div>
            <div>已取消课程</div>
          </div>
          <div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#722ed1' }}>
              {totalCredits}
            </div>
            <div>总学分</div>
          </div>
        </div>
      </Card>

      {/* 预订列表 */}
      <Card
        title={
          <Space>
            <BookOutlined />
            课程预订列表
          </Space>
        }
        style={{ marginTop: 16 }}
      >
        <Table
          columns={bookingColumns}
          dataSource={bookings}
          rowKey="id"
          loading={bookingsLoading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条预订记录`,
            defaultPageSize: 10
          }}
        />
      </Card>
    </div>
  );
};

export default StudentDetail;